//@flow
import { 
    Platform,
    Linking,
    PlatformOSType,
 } from "react-native";
import * as Config from "../config/config";
import { SCREEN_SIZE } from "./constant/size";

/**
 * 常用无法归类的方法
 */

/**当前设备是否是iphone X刘海系列手机 */
export const isIPhoneXSeries = ():boolean => {
    // iPhoneX Xs
    const X_WIDTH = 375;
    const X_HEIGHT = 812;

    // iPhoneXR XsMax
    const XR_WIDTH = 414;
    const XR_HEIGHT = 896;

    const SCREEN_WIDTH = SCREEN_SIZE.width;
    const SCREEN_HEIGHT= SCREEN_SIZE.height;

    return Platform.OS === 'ios' && 
             (
                (
                    (SCREEN_HEIGHT === X_HEIGHT && 
                    SCREEN_WIDTH === X_WIDTH) || //是否为iphoneX Xs 竖屏
                    (SCREEN_HEIGHT === X_WIDTH && 
                    SCREEN_WIDTH === X_HEIGHT)   //是否为iphoneX Xs 横屏
                ) ||
                (
                    (SCREEN_HEIGHT === XR_HEIGHT && 
                    SCREEN_WIDTH === XR_WIDTH) || //是否为iphoneXR XsMax 竖屏
                    (SCREEN_HEIGHT === XR_WIDTH && 
                    SCREEN_WIDTH === XR_HEIGHT)   //是否为iphoneXR XsMax 横屏
                )
             )
}

/**判断该色彩是否为浅色系
 * 颜色必须为 “#000000” 或 “rgb(0,0,0)” 或 “rgba(0,0,0,0)”其一
 * @returns true:表示‘浅色’  false：表示‘深色’
 */
export const isLightColor = (color:string):boolean=>{
    /**
     * color可能包含下列几种情况
     * 1，#000000 ：一般的16进制rgb
     * 2，#00000000:带有透明度16进制rgba
     * 3，rgb(10,10,10):一般10进制rgb
     * 4，rbga(10,10,10,0.5):一般10进制rgba
     * 5，‘yellow’：一般字符串颜色  - 禁止这种参数
     */
    let r:number = 0;
    let g:number = 0;
    let b:number = 0;

    if(color.indexOf('#')==0 && color.length == 7){
        r = parseInt(color.slice(1,3),16)
        g = parseInt(color.slice(3,5),16)
        b = parseInt(color.slice(5,-1),16)
        console.log(`rbg:(${r},${g},${b}) -- ${color}`)
    }else if(color.indexOf('rgb')==0){
        let startIndex:number = 4;
        let colorLength:number = color.length;
        let colorString:string = '';
        if(color.indexOf('rgba')==0){
            startIndex ++;//从rbga( + )开始提取有效字符,中间的有效数据   
        }
        colorString = color.slice(startIndex,colorLength-1);
        //将210，210，210 或者 210，210，210，0.4 这样数据提取前三项作为r、g、b
        let tmpArr:Array<number> = colorString.split(',')
        r = parseInt(tmpArr[0])
        g = parseInt(tmpArr[1])
        b = parseInt(tmpArr[2])
    }else{
        
        throw new Error(`颜色值格式必须为:'#000000','rgb(0,0,0)','rgba(0,0,0,0)',不支持当前：${color}的格式`)
    }

    return r*0.299+g*0.578+b*0.114 >= 192
}

/**
 * 判断是否为空对象
 * {} null undefined
 */
export function isEmptyObject(obj:any):boolean{
    
}

/**
 * 将对象类型拼凑成get请求的字符串
 * key=value&key=value
 */
export function handleGetParams(params:{[key:string]:string}):string{
    let tmp : {[key:string]:string} = {...params};
    /**请求参数所有键值对 */
    let keys : Array<string> = Object.keys(tmp);
    /**将参数整理成数组，每一个键值作为一个元素,最后利用数组的方法拆分 */
    let kvArr: Array<string> = [];
    try {
        for(let i of keys){
            let kv:string = `${i}=${tmp[i]}`;
            kvArr.push(kv);
        }    
    } catch (error) {
        console.log(`解析拼凑请求get参数异常，${arguments.callee.toString()}\n异常内容${JSON.stringify(error)}`)
        throw error;
    }
    
    return kvArr.join('&')
}

/**
 * 将对象类型转为form表单数据
 */
export function handlePostParams(params:{[key:string]:string}):FormData{
    let tmp : {[key:string]:string} = {...params};
    /**请求参数所有键值对 */
    let keys : Array<string> = Object.keys(tmp);
    /**构造一个表单数据 */
    let form : FormData = new FormData();
    try {
        for(let i of keys){
            form.append(i,tmp[i])
        }
    } catch (error) {
        console.log(`解析拼凑请求post参数异常，${arguments.callee.toString()}\n异常内容${JSON.stringify(error)}`)
        throw error;
    }
    return form;
}

/**
 * 数字判空处理
 */
export function isEffectiveNumber(value:number):boolean{
    //有能是数字类型，也可能是字符串0
    return typeof value == 'number' || value == '0';

}

/**
 * component组件，action名字生成器
 * 
 * 因为action的名字是全局统一的，因此一定要加上前缀加以区分，前缀就是文件名
 */
export const genrateAction = (typeName:string,namespace:string)=>{
    return `${namespace}${typeName}`
}

/**
 * app二进制文件版本与app store比较
 * 
 * 版本信息均为 x.x.x ：三位数
 */
export function companyBinaryVersion(local:string,remote:string){
    let localArr : Array<number> ;
    let remoteArr: Array<number> ;
    try {
        localArr = local.split('.');
        remoteArr= remote.split('.');
        if(localArr.length==3 && remoteArr.length == 3){
            if(remoteArr[0]>localArr[0]){
                return true
            }else if(remoteArr[0]==localArr[0] && remoteArr[1]>localArr[1]){
                return true;
            }else if(remoteArr[0]==localArr[0] && remoteArr[1]==localArr[1] && remoteArr[2]>localArr[2]){
                return true
            }else{
                return false;
            }
        }else{
            return false;
        }
    } catch (error) {
        return false;
    }
}

/**
 * 跳转到应用商店
 */
export async function linkToAppStore(){
    let platform : PlatformOSType = Platform.OS;
    let link : string = Config.LINK_TO_STORE;
    let canOpen :boolean = await Linking.canOpenURL(Config.LINK_TO_STORE)
    switch(platform){
        case 'ios':           
        case 'android':
            if(canOpen){
                Linking.openURL(Config.LINK_TO_STORE)
            }else{
                console.log('无法跳转到应用商店')
            }
            break
        default :
            console.log('不支持该平台')
    }
    
}

/**
 * 生成GUID
 */
export function genId(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      }).toUpperCase();
   }